package com.itheima.pay.controller;

import com.github.wxpay.sdk.WXPay;
import com.itheima.pay.config.WXPayConfigCustom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("wxpay")
public class WxpayController {

    // 下单
    @GetMapping("unifiedorder")
    public Map<String, String> unifiedorder(String orderNo) throws Exception {
        WXPayConfigCustom config = new WXPayConfigCustom();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "餐掌柜-餐饮消费");
        data.put("out_trade_no", orderNo); //2016090910595900000012
        data.put("total_fee", "1"); // 单位：分
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://www.example.com/wxpay/notify"); //回调通知
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    // 查询支付状态
    @GetMapping("orderquery")
    public Map orderquery(String orderNo) throws Exception {
        WXPayConfigCustom config = new WXPayConfigCustom();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", orderNo);

        //交易成功判断条件： return_code、result_code和trade_state都为SUCCESS
        Map<String, String> map = wxpay.orderQuery(data);
        return map;
    }

    // 退款
    @GetMapping("refund")
    public Map refund(String orderNo,String refundNo, String refundMoney) throws Exception {
        WXPayConfigCustom config = new WXPayConfigCustom();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", orderNo);
        data.put("out_refund_no", refundNo);
        data.put("total_fee", "1");
        data.put("refund_fee", refundMoney);
        data.put("refund_desc", "退款原因");

        Map<String, String> map = wxpay.refund(data);
        return map;
    }
}
